package aspect;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import pojo.Info;

@Component
@Aspect
public class DigestAspect {
	private final String p1="execution(* controller.InfoController.regist(..))";
	private final String p2="execution(* controller.InfoController.login(..))";
	private MessageDigest digest;
	public DigestAspect(){
		try {
			digest = MessageDigest.getInstance("md5");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}
	@Around(value=p1)
	public Object regist(ProceedingJoinPoint point){
		Object object = null;
		Info info = (Info)point.getArgs()[0];
		info.setPwd(process(info.getPwd()));
		try {
			object = point.proceed(new Object[]{info});
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return object;
	}
	
	@Around(value=p2)
	public Object login(ProceedingJoinPoint point){
		Object object = null;
		String s = (String)point.getArgs()[1];
		String ss = process(s);
		try {
			object = point.proceed(new Object[]{point.getArgs()[0], ss});
		} catch (Throwable e) {
			e.printStackTrace();
		}
		
		return object;
	}
	
	private String process(String s){
		byte[] bs;
		String ss = null;
		try {
			bs = digest.digest(s.getBytes("ISO-8859-1"));
			ss = new String(bs,"ISO-8859-1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return ss;
	}

}
